<template>
  <div class="box">
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">  
          <el-input clearable placeholder="请输入内容" v-model="queryInfo.query" @clear="getUserList" >
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">  
          <el-button type="primary" @click="btnAddUser">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="50px"></el-table-column>
        <el-table-column prop="username" label="姓名" ></el-table-column>
        <el-table-column prop="email" label="邮箱" ></el-table-column>
        <el-table-column prop="mobile" label="电话" ></el-table-column>
        <el-table-column prop="role_name" label="角色" ></el-table-column>
        <el-table-column label="状态" >
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="195px">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="btnEditUser(scope.row.id)"></el-button>
            <!-- 删除 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="btnDeleteUser(scope.row.id)"></el-button>
            <!-- 分配角色 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="btnAssignRole(scope.row)"></el-button>
            </el-tooltip>     
          </template>        
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1,2,5,10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>  
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="40%"
      @close="addDialogClosed">
      <!-- 内容主题区 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" class="demo-ruleForm">
        <!-- prop 是验证规则 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>       
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="btnCancelAdd">取 消</el-button>
        <el-button type="primary" @click="btnSaveAdd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="40%"
      @close="editDialogClosed">
      <!-- 内容主题区 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px" class="demo-ruleForm">
        <!-- prop 是验证规则 -->
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>       
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="btnCancelEdit">取 消</el-button>
        <el-button type="primary" @click="btnSaveEdit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="assignRoleDialogVisible"
      width="40%"
      @close="assignRoleDialogClosed">
      <!-- 内容主题区 -->
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="btnCancelAssignRole">取 消</el-button>
        <el-button type="primary" @click="btnSaveAssignRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义校验规则
    var validateEmail = (rule, value, callback) => {
      let reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error("邮箱格式不正确"));
      }
    };
    var validateMobile = (rule, value, callback) => {
      let reg =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error("手机号码格式不正确"));
      }
    };
    return {
      // 获取用户列表的参数
      queryInfo: {
        // 搜索请求参数
        query: "",
        // 当前页数
        pagenum: 1,
        // 每页显示多少数据
        pagesize: 5,
      },
      // 获取的用户列表
      userList: [],
      // 总数据条数
      total: 0,
      // 添加用户对话框是否打开
      addDialogVisible: false,
      // 添加用户表单
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      addFormRules: {
        // 验证用户名是否合法
        username: [
          { required: true, message: "请输入登录名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        // 验证密码是否合法
        password: [
          { required: true, message: "请输入登录密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            validator: validateEmail,
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            validator: validateMobile,
            trigger: "blur",
          },
        ],
      },
      // 修改用户对话框是否打开
      editDialogVisible: false,
      // 修改用户表单
      editForm: {},
      editFormRules: {
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            validator: validateEmail,
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            validator: validateMobile,
            trigger: "blur",
          },
        ],
      },
      // 分配角色对话框是否打开
      assignRoleDialogVisible: false,
      // 即将分配角色的用户信息
      userInfo: {},
      // 所有角色列表
      rolesList: [],
      // 分配角色界面下拉列表框中选中的角色id
      selectRoleId: "",
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 获取用户列表 如果queryInfo.query为空，则全部查询，queryInfo.query不为空，则参数查询
    async getUserList() {
      // get 方法返回一个 promise 对象
      const { data: res } = await this.$axios.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 改变每页显示多少行
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 改变当前页码
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 监听 switch 开关状态的改变
    async userStateChanged(userInfo) {
      const { data: res } = await this.$axios.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (res.meta.status != 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
    },
    // 添加用户按钮
    btnAddUser() {
      this.addDialogVisible = true;
    },
    // 添加用户对话框关闭后触发的事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 添加用户界面取消按钮
    btnCancelAdd() {
      this.addDialogVisible = false;
    },
    // 添加用户界面确定按钮
    btnSaveAdd() {
      // 表单验证成功 valid 为 true
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        // 发起网络请求添加用户
        // post 返回值为promise 因此用异步async/await
        const { data: res } = await this.$axios.post("users", this.addForm);
        // 创建失败
        if (res.meta.status != 201) {
          return this.$message.error(res.meta.msg);
        }
        // 创建成功
        this.$message.success(res.meta.msg);
        // 关闭对话框
        this.addDialogVisible = false;
        // 刷新数据
        this.getUserList();
      });
    },
    // 修改用户按钮
    async btnEditUser(id) {
      this.editDialogVisible = true;
      // 根据 id 发起网络请求获取信息
      // get 返回值为promise 因此用异步async/await
      const { data: res } = await this.$axios.get(`users/${id}`);
      // 请求失败
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg);
      }
      // 请求成功
      this.$message.success(res.meta.msg);
      this.editForm = res.data;
    },
    // 修改用户对话框关闭后触发的事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 修改用户界面取消按钮
    btnCancelEdit() {
      this.editDialogVisible = false;
    },
    // 修改用户界面确定按钮
    btnSaveEdit() {
      // 表单验证成功 valid 为 true
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        // 发起网络请求修改用户
        // put 返回值为promise 因此用异步async/await
        const { data: res } = await this.$axios.put(
          `users/${this.editForm.id}`,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        );
        // 修改失败
        if (res.meta.status != 200) {
          return this.$message.error(res.meta.msg);
        }
        // 修改成功
        this.$message.success(res.meta.msg);
        // 关闭对话框
        this.editDialogVisible = false;
        // 刷新数据
        this.getUserList();
      });
    },
    // 删除用户按钮
    btnDeleteUser(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 发起删除的网络请求
          const { data: res } = await this.$axios.delete(`users/${id}`);
          // 删除失败
          if (res.meta.status != 200) {
            return this.$message.error(res.meta.msg);
          }
          // 删除成功
          this.$message.success(res.meta.msg);
          // 刷新数据
          this.getUserList();
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    async btnAssignRole(userInfo) {
      this.userInfo = userInfo;
      // 在展示对话框之前获取所有角色列表
      // get 方法返回一个 promise 对象
      const { data: res } = await this.$axios.get("roles");
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg);
      }
      this.rolesList = res.data;
      // 展开对话框
      this.assignRoleDialogVisible = true;
    },
    // 对话框关闭后触发的事件
    assignRoleDialogClosed() {
      this.selectRoleId = "";
      this.userInfo = {};
    },
    // 分配角色界面取消按钮
    btnCancelAssignRole() {
      this.assignRoleDialogVisible = false;
    },
    // 分配角色界面确定按钮
    async btnSaveAssignRole() {
      if (!this.selectRoleId) {
        return this.$message.error("请选择要分配的角色！");
      }
      const { data: res } = await this.$axios.put(
        `users/${this.userInfo.id}/role`,
        { rid: this.selectRoleId }
      );
      // 分配失败
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg);
      }
      // 分配成功
      this.$message.success(res.meta.msg);
      // 关闭对话框
      this.assignRoleDialogVisible = false;
      // 刷新数据
      this.getUserList();
    },
  },
};
</script>

<style scoped>
</style>